package com.ghsc.ghxc.jsb.ui.message

import android.graphics.Typeface
import android.os.Bundle
import android.view.View
import androidx.fragment.app.Fragment
import androidx.viewpager.widget.ViewPager
import com.cn.appcore.adapter.PagerAdapter
import com.cn.appcore.base.BaseVMFragment
import com.cn.appcore.event.RxBus
import com.cn.appcore.event.RxBusBean
import com.cn.appcore.event.SchedulerTransformer
import com.cn.appcore.ext.getCompatColor
import com.cn.appcore.ext.loge
import com.flyco.tablayout.listener.OnTabSelectListener
import com.ghsc.ghxc.jsb.R
import com.ghsc.ghxc.jsb.config.CustSignKey
import com.ghsc.ghxc.jsb.config.UserManager
import com.ghsc.ghxc.jsb.databinding.FragmentMessageBinding
import com.ghsc.ghxc.jsb.ui.message.activity.ChatConfSetActivity
import com.ghsc.ghxc.jsb.ui.message.activity.CreateGroupNameTypeActivity
import com.ghsc.ghxc.jsb.ui.message.activity.FriendsListActivity
import com.ghsc.ghxc.jsb.ui.message.activity.MyGroupListActivity
import com.ghsc.ghxc.jsb.ui.message.activity.SearchChatActivity
import com.ghsc.ghxc.jsb.ui.message.fragment.YunXinCharListFragment
import com.ghsc.ghxc.jsb.ui.message.view.ChatTopPopVIew
import com.lxj.xpopup.XPopup
import com.lxj.xpopup.util.XPopupUtils
import com.netease.nimlib.sdk.NIMClient
import com.netease.nimlib.sdk.auth.AuthServiceObserver
import com.netease.nimlib.sdk.msg.SystemMessageService
import com.netease.nimlib.sdk.msg.constant.SystemMessageType

/**
 * 项目：GuoHuaJsb
 * 包名：com.ghsc.ghxc.jsb.ui.message
 * 类名：MessageFragment
 * 创建时间：2024/4/23 15:00
 * 创建人 @author： xiaolin
 * 描述 ：Todo...
 */
class MessageFragment : BaseVMFragment<MessageViewModel, FragmentMessageBinding>(R.layout.fragment_message),
    OnTabSelectListener {
    override fun attachVMClass(): Class<MessageViewModel>? {
        return MessageViewModel::class.java
    }

    override fun lazyLoad() {
    }



    override fun onResume() {
        super.onResume()
        NIMClient.getService(AuthServiceObserver::class.java).observeOnlineStatus(
            { status ->
                loge("登录状态="+status.desc+"xxx="+status.value)
                //获取状态的描述
                if ( status.value==6) {
                    // 被踢出、账号被禁用、密码错误等情况，自动登录失败，需要返回到登录界面进行重新登录操作
                    val types: MutableList<SystemMessageType> = ArrayList()
                    types.add(SystemMessageType.AddFriend)
                    // 查询“添加好友”类型的系统通知未读数总和
                    val count = NIMClient.getService(SystemMessageService::class.java)
                        .querySystemMessageUnreadCountByType(types)
                    if(count>0){
                        if(count>=99){
                            binding.tvCount.visibility= View.VISIBLE
                            binding.tvCountNum.visibility= View.GONE
                            binding.tvCount.text="99+"
                        }else{
                            binding.tvCountNum.visibility= View.VISIBLE
                            binding.tvCount.visibility= View.GONE
                            binding.tvCountNum.text=count.toString()
                        }
                    }else{
                        binding.tvCount.visibility= View.GONE
                        binding.tvCountNum.visibility= View.GONE
                    }
                }
            }, true
        )


    }
    var mList: MutableList<String> = ArrayList()
    var mAdapter: PagerAdapter? = null
    private val mFragments: MutableList<Fragment> = ArrayList()
    override fun initView(savedInstanceState: Bundle?) {
        mList.clear()
        mList.add("消息")
        mFragments.clear()
        YunXinCharListFragment.getInstance()?.let { mFragments.add(it) }
        mAdapter = PagerAdapter(childFragmentManager, mList, mFragments)
        binding.vpType.adapter = mAdapter
        binding.slitab.setViewPager(binding.vpType)
        binding.slitab.currentTab = 0
        binding.vpType.addOnPageChangeListener(object : ViewPager.OnPageChangeListener {
            override fun onPageScrolled(
                position: Int,
                positionOffset: Float,
                positionOffsetPixels: Int
            ) {
            }

            override fun onPageSelected(position: Int) {
                tabIndex(position)
            }

            override fun onPageScrollStateChanged(state: Int) {}
        })
        tabIndex(0)
        rxBusSubscription = RxBus.getDefault().toObservable(RxBusBean::class.java)
            .compose(SchedulerTransformer())
            .subscribe{ rxBusBean ->
                if (rxBusBean.id == CustSignKey.CHAT_UNREAD_NUM && rxBusBean.sign == CustSignKey.CHAT_UNREAD_NUM) {
                    var count= UserManager.getImCount()
                    count += 1
                    UserManager.setImCount(count)
                    if(count>0){
                        if(count>=99){
                            binding.tvCount.visibility=View.VISIBLE
                            binding.tvCountNum.visibility=View.GONE
                            binding.tvCount.text="99+"
                        }else{
                            binding.tvCountNum.visibility=View.VISIBLE
                            binding.tvCount.visibility=View.GONE
                            binding.tvCountNum.text=count.toString()
                        }
                    }else{
                        binding.tvCount.visibility=View.GONE
                        binding.tvCountNum.visibility=View.GONE
                    }
                }
            }
    }
    override fun onTabSelect(position: Int) {
        tabIndex(position)
    }

    override fun onTabReselect(position: Int) {

    }
    private fun tabIndex(index: Int) {
        for (i in mList.indices) {
            if (i == index) {
                val tv = binding.slitab.getTitleView(i)
                tv.textSize = 17f
                tv.typeface = Typeface.defaultFromStyle(Typeface.BOLD) //加粗
            } else {
                val tv2 = binding.slitab.getTitleView(i)
                tv2.textSize = 15f
                tv2.typeface = Typeface.defaultFromStyle(Typeface.NORMAL)
            }
        }
    }

    override fun initClickListener() {
        super.initClickListener()
        binding.imgBtnFriends.setOnClickListener {
            //我的好友
            startActivity(FriendsListActivity().javaClass)

        }
        binding.imgBtnList.setOnClickListener {

            XPopup.Builder(activity)
                .atView(binding.imgBtnList)
                .hasShadowBg(false) // 去掉半透明背景
                .offsetY(XPopupUtils.dp2px(activity, 2f))
                .navigationBarColor(getCompatColor(R.color.bg_dark_color))
                .asCustom(
                    ChatTopPopVIew(requireActivity(),
                        tvBtnNewGroup={
                            //创建群聊
                            startActivity(CreateGroupNameTypeActivity().javaClass)

                        },
                        tvBtnAddFriends={
                            //加好友/群
                            startActivity(SearchChatActivity().javaClass)

                        },
                        tvBtnGroup={
                            //我的群聊
                            startActivity(MyGroupListActivity().javaClass)
                        },
                        tvBtnSet={
                            startActivity(ChatConfSetActivity().javaClass)
                        }
                    )
//                                .setArrowOffset(-XPopupUtils.dp2px(getContext(), 40))  //气泡箭头偏移
//                                .setBubbleBgColor(Color.RED)  //气泡背景
                        .setArrowWidth(XPopupUtils.dp2px(activity, 5f))
                        .setArrowHeight(XPopupUtils.dp2px(activity, 6f))
//                                .setBubbleRadius(100)
                        .setArrowRadius(XPopupUtils.dp2px(activity, 3f))
                )
                .show()



        }
    }
}